package com.example.test_witns;

import static com.tencent.imsdk.v2.V2TIMMessage.V2TIM_ELEM_TYPE_TEXT;

import android.content.Context;
import android.content.pm.PackageManager;
import android.database.CursorWindow;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.OnBackPressedCallback;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.example.test_witns.databinding.ActivityBottomNavigationViewAcitivityBinding;
import com.example.test_witns.pojo.BannerDataInfo;
import com.example.test_witns.utils.MyInfosHelper;
import com.example.test_witns.utils.NotificationUtils;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.tencent.imsdk.v2.V2TIMAdvancedMsgListener;
import com.tencent.imsdk.v2.V2TIMCallback;
import com.tencent.imsdk.v2.V2TIMConversation;
import com.tencent.imsdk.v2.V2TIMConversationListener;
import com.tencent.imsdk.v2.V2TIMManager;
import com.tencent.imsdk.v2.V2TIMMessage;
import com.tencent.imsdk.v2.V2TIMSDKConfig;
import com.youth.banner.Banner;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class BottomNavigationViewActivity extends AppCompatActivity {
    private static final int NOTIFICATION_PERMISSION_CODE = 100;
    private long mBackPressedTime;
    private int message_counter = 0;
    private static final int BACK_PRESS_DELAY = 2000; // 2000毫秒，即2秒
    private V2TIMMessage latestMsg;
    V2TIMConversation latestConversation;
    private int msgReadyNum;
    private int conversationReadyNum;

    private ActivityBottomNavigationViewAcitivityBinding binding;

    private Banner banner;
    private final List<BannerDataInfo> bannerDataInfos = new ArrayList<>();
    public static boolean onLogin = false;
    private OnRecvMsgListener onRecvMsgListener;
    private OnConversationChangedListener onConversationChangedListener;

    private interface OnRecvMsgListener{
        void onRecvMsg();
    }

    private interface OnConversationChangedListener{
        void onConversationChanged(V2TIMConversation conversation);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityBottomNavigationViewAcitivityBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        MyInfosHelper myInfosHelper = new MyInfosHelper(BottomNavigationViewActivity.this);

        /*ViewPager2 viewPager = findViewById(R.id.home_view_pager);

        // 设置适配器
        ScreenSlidePagerAdapter adapter = new ScreenSlidePagerAdapter(this);
        viewPager.setAdapter(adapter);
        //viewPager.setOffscreenPageLimit(3);

        viewPager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                Toast.makeText(BottomNavigationViewActivity.this, "选择了页面: " + position, Toast.LENGTH_SHORT).show();
            }
        });*/

        onRecvMsgListener = new OnRecvMsgListener() {
            @Override
            public void onRecvMsg() {

            }
        };
        onConversationChangedListener = new OnConversationChangedListener() {
            @Override
            public void onConversationChanged(V2TIMConversation conversation) {

            }
        };

        /* cursor大小不够会导致sqlite单次返回数据包容量不够, 导致dump, 但是这样性能不好, 限制用户单次返回数据量可能更好, 压缩图片可能也不错 */
        try {
            Field field = CursorWindow.class.getDeclaredField("sCursorWindowSize");
            field.setAccessible(true);
            field.set(null, 5 * 1024 * 1024);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Window window = getWindow();

        V2TIMManager.getMessageManager().addAdvancedMsgListener(new V2TIMAdvancedMsgListener() {
            /**
             * @param msg
             */
            @Override
            public void onRecvNewMessage(V2TIMMessage msg) {
                super.onRecvNewMessage(msg);
                latestMsg = msg;
                msgReadyNum++;
                notifyUserNewMsg();
            }

        });

        V2TIMManager.getConversationManager().addConversationListener(new V2TIMConversationListener() {
            @Override
            public void onConversationChanged(List<V2TIMConversation> list) {
                // 会话信息发生变化
                for (V2TIMConversation conversation : list) {
                    // 检查是否是C2C会话
                    if (conversation.getType() == V2TIMConversation.V2TIM_C2C) {
                        latestConversation = conversation;
                        conversationReadyNum++;
                        notifyUserNewMsg();
                    }
                }
            }
        });

        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);

//        window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
//        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);

        Objects.requireNonNull(getSupportActionBar()).hide();

        NotificationUtils.createNotificationChannel(this);
        //checkNotificationPermission(); // Android 13+ 权限检查


        BottomNavigationView navView = findViewById(R.id.nav_view);
        AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(
                R.id.navigation_home, R.id.navigation_devices, R.id.navigation_friends, R.id.navigation_mine)
                .build();
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_activity_bottom_navigation_view_acitivity);
        NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);
        NavigationUI.setupWithNavController(binding.navView, navController);

        boolean isLogin = myInfosHelper.checkIfLogin();

        if (isLogin && !onLogin){
            myInfosHelper.loadMyInfos(new MyInfosHelper.GetMyInfos() {
                @Override
                public void onLoadingMyInfos(String email ,String sig, String name, String uuid, byte[] avatar, String uri, String url) {

                    V2TIMSDKConfig config = new V2TIMSDKConfig();
                    config.setLogLevel(V2TIMSDKConfig.V2TIM_LOG_INFO);
                    V2TIMManager.getInstance().initSDK(BottomNavigationViewActivity.this,1600066337, config);

                    V2TIMManager.getInstance().login(email, sig, new V2TIMCallback() {
                        @Override
                        public void onSuccess() {
                            String message = "登录状态正常";
                            toast_Confirm_Style(message);
                            onLogin = true;
                        }

                        @Override
                        public void onError(int i, String s) {
                            String message = "登录状态已过期, 请重新登录";
                            toast_Prohibited_Style(message);
                            myInfosHelper.deleteMyInfosTable();
                        }
                    });
                }
            });
        }

        getOnBackPressedDispatcher().addCallback(this, new OnBackPressedCallback(true) {
            @Override
            public void handleOnBackPressed() {
//                if (!navController.navigateUp()){
//                    finish();
//                }else {
//                    while (navController.navigateUp());
//                    navController.navigate(R.id.action_navigation_todo_to_navigation_home);
//                }
                  long currentTime = System.currentTimeMillis();

                  // 检查两次按下返回键的时间间隔是否小于设定的延迟
                  if (currentTime - mBackPressedTime <= BACK_PRESS_DELAY) {
                      // 如果小于延迟，则退出 Activity
                      finish();
                      // 如果需要，可以在这里调用 `super.onBackPressed()` 来让系统处理返回操作
                  } else {
                      // 如果大于延迟，提示用户再次按下返回键退出
                      Toast.makeText(BottomNavigationViewActivity.this, "再按一次退出应用", Toast.LENGTH_SHORT).show();
                      // 更新按下返回键的时间
                      mBackPressedTime = currentTime;

                  }
            }
        });


    }

    public void notifyUserNewMsg(){
        if (msgReadyNum > 0 && conversationReadyNum > 0){
            String userID = latestConversation.getUserID();
            if (latestMsg.getSender().equals(userID)) {
                int unreadCount = latestConversation.getUnreadCount();
                String imageUrl = latestMsg.getFaceUrl();
                if (latestMsg.getElemType() == V2TIM_ELEM_TYPE_TEXT){
                    if (unreadCount > 1){
                        loadAvatarAndSendNotification(getApplicationContext(), imageUrl,
                                latestMsg.getNickName(), "[" + unreadCount + "条]" + latestMsg.getNickName() + ": " + latestMsg.getTextElem().getText());
                    }else {
                        loadAvatarAndSendNotification(getApplicationContext(), imageUrl,
                                latestMsg.getNickName(), latestMsg.getNickName() + ": " + latestMsg.getTextElem().getText());
                    }
                }else {
                    if (unreadCount > 1){
                        loadAvatarAndSendNotification(getApplicationContext(), imageUrl,
                                latestMsg.getNickName(),
                                "[" + unreadCount + "条]" + latestMsg.getNickName() + ": " + "[特殊消息]");
                    }else {
                        loadAvatarAndSendNotification(getApplicationContext(), imageUrl,
                                latestMsg.getNickName(),
                                latestMsg.getNickName() + ": " + "[特殊消息]");
                    }
                }
            }
        }
    }

    private void toast_Confirm_Style(String message) {
        View customView = LayoutInflater.from(this).inflate(R.layout.custom_toast_confirm_layout, null);
        TextView toastText = customView.findViewById(R.id.toast_message);
        toastText.setText(message);

        Toast toast = new Toast(this);
        toast.setView(customView);
        toast.setDuration(Toast.LENGTH_SHORT);
        toast.setGravity(Gravity.TOP, 0, 40); // 设置在屏幕顶部
        toast.show();
    }

    private void toast_Prohibited_Style(String message) {
        View customView = LayoutInflater.from(this).inflate(R.layout.custom_toast_prohibited_layout, null);
        TextView toastText = customView.findViewById(R.id.toast_message);
        toastText.setText(message);

        Toast toast = new Toast(this);
        toast.setView(customView);
        toast.setDuration(Toast.LENGTH_SHORT);
        toast.setGravity(Gravity.TOP, 0, 40); // 设置在屏幕顶部
        toast.show();
    }

    private void checkNotificationPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.POST_NOTIFICATIONS)
                    != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(
                        this,
                        new String[]{android.Manifest.permission.POST_NOTIFICATIONS},
                        NOTIFICATION_PERMISSION_CODE
                );
            }
        }
    }

    // 处理权限结果
    @Override
    public void onRequestPermissionsResult(int code, @NonNull String[] permissions, @NonNull int[] results) {
        super.onRequestPermissionsResult(code, permissions, results);
        if (code == NOTIFICATION_PERMISSION_CODE) {
            if (results.length > 0 && results[0] == PackageManager.PERMISSION_GRANTED) {
                // 权限已授予
            }
        }
    }

    public static void loadAvatarAndSendNotification(Context context, String imageUrl, String title, String content) {
        new Thread(() -> {
            try {
                // 同步加载网络图片
                Bitmap avatarBitmap = Glide.with(context)
                        .asBitmap()
                        .load(imageUrl)
                        .apply(RequestOptions.bitmapTransform(new RoundedCorners(10)))
                        .submit(60, 60) // 限制尺寸
                        .get(); // 注意：需在后台线程执行

                NotificationUtils.sendNotificationWithAvatar(context, avatarBitmap, title, content);
            } catch (Exception e) {
                // 加载失败时使用默认头像
                NotificationUtils.sendNotificationWithAvatar(context, null, title, content);
            }
        }).start();
    }

}